$(function(){
        /* 设置ajax公用属性 */
        $.ajaxSetup({
              type: "POST", 
              dataType:'json'
          });
        
        
        /* 页面初始化时的处理 */
        /* $('#loginName').focus(); */
        if($.cookie("CERP_LESSASS_N")!=undefined&&$.cookie("CERP_LESSASS_P")!=undefined){
        
          /* cookie中有值时，选中记住密码checkbox,给用户名和密码赋上值 */
          if(($.cookie("CERP_LESSASS_N")!='null')&&($.cookie("CERP_LESSASS_P")!='null')){
            $('#rememberPwd').attr("checked","checked");
            
            $('#loginName').val($.base64.atob($.cookie("CERP_LESSASS_N")));
            $('#loginPwd').val($.base64.atob($.cookie("CERP_LESSASS_P")));
          }
          //访问登录页面时，若登录状态为‘1’时，直接跳转到首页
          var state = $.base64.atob($.cookie("CERP_LESSASS_D"));
          if(state == '1'){
            
          }else{
            
          }
        }  
        
        /* 键盘事件处理 */
        document.onkeydown = function(e){ 
            var ev = document.all ? event :(window.event ? window.event : e); 
            if(ev.keyCode==13) {
              //提交表单
            	submitForm();  
            }
        }
        
        
        $('#kaptchaImage').click(function () {  //生成验证码  
                $(this).hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
        });
        
        /* 登录操作处理 */
        $("#login_button").click(function(){
        	submitForm();
        });
        
        
	});    
    
//校验电子邮箱格式
function checkEmail(sync){
	var email = $("#loginName").val();			//电子邮箱
	var emailRegex=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	loadingBgAdd();
	//验证电子邮箱
  		if(email == ""){			//判断是否为空
  			$('#loginName').val("");
  			$('#loginName').css("border-color","red");
			$('#loginName').attr("placeholder","请输入正确格式的电子邮箱");
			loadingBgRemove();
  			return false;
  		}else{						
  			if(emailRegex.test(email)){		//格式正确,判断唯一性
  				if(email.length>50){		//验证字符串长度
  					$('#loginName').val("");
  	    			$('#loginName').css("border-color","red");
  					$('#loginName').attr("placeholder","邮箱不大于50个字符");
  					loadingBgRemove();
  					return false;
  				}else{
  					return true;
  				}
  			}else{		//格式不正确
	   			$('#loginName').val("");
	   			$('#loginName').css("border-color","red");
				$('#loginName').attr("placeholder","请输入正确格式的电子邮箱");
				loadingBgRemove();
	   			return false;
  			}
  		}
}

//校验电子邮箱格式
function checkIsEmail(sync){
    var email = $("#loginName").val();			//电子邮箱
    var emailRegex=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    loadingBgAdd();
    //验证电子邮箱
	if(emailRegex.test(email)){		//格式正确 是邮箱
		$('#loginName').val("");
		$('#loginName').css("border-color","red");
		$('#loginName').attr("placeholder","请输入注册时的证件号码");
		loadingBgRemove();
		return false;
	}else{		//格式不正确 不是邮箱
		loadingBgRemove();
		return true;
	}
}

	function submitForm(){
		loadingBgAdd();
	  if(checkEmpty() && checkIsEmail()){
          $('input[name="loginPwd"]').val($.md5($('#loginPwd').val()));
	      var form=$("#loginForm").serialize();
	      $.ajax({
	        type:'post',
	        dataType:'json',
	        url:ctx+'/login/loginSuccess',
	        data:form,
	        async: true,
	        success:function(data){
	          if  (data.success){
					//操作cookie,如果选中了记住密码，向cookie添加值，反之，从cookie中删除值
					if($('#rememberPwd').prop("checked")){
					  $.cookie("CERP_LESSASS_N", $.base64.btoa($('#loginName').val()),{expires:1,path:'/',domain:hostName});   
					  $.cookie("CERP_LESSASS_P", $.base64.btoa($('#loginPwd').val()),{expires:1,path:'/',domain:hostName});   
					}else{
					  $.cookie("CERP_LESSASS_N",null,{expires:0,path:'/',domain:hostName});  
					  $.cookie("CERP_LESSASS_P",null,{expires:0,path:'/',domain:hostName});  
					}
					//loginSuccess();
					  var userName = data.obj.userName;
					  var returnUrl = data.obj.returnUrl;
					
					  //设置cookie的失效时间为20分钟
					  var date = new Date();
					  date.setTime(date.getTime() + (1 * 20 *60 * 1000));  
					 
				if (data.msg == "post"){
				  	var formData=data.obj.formData;
				  	
				  	initPostData(formData,returnUrl);
				  
				$('#hidForm').submit();
			}else {
			
				window.location.href=returnUrl;
			}
	            
	        }else{
	            if (data.msg=="codeError"){
	            	
	              $('#verificationCode').val("");
	              $('#verificationCode').focus();
	              $('#verificationCode').attr("placeholder","验证码不正确");
	              countCodeError++;
	              if(countCodeError>=1){
	                $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	                countCodeError=0;
	              }
	              loadingBgRemove();//关闭遮盖层
	            }else if (data.msg=="locked"){
	            	$('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	              inputAssert($('#loginPwd'));
	              $('#loginPwd').val("");
	              $('#loginPwd').attr("placeholder","用户已被锁定,一小时后重试");
	              loadingBgRemove();//关闭遮盖层
	            }else if(data.msg=="errorLogin" || data.msg=="errorLoginName"){
	              $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	              inputAssert($('#loginPwd'));
	              $('#loginPwd').val("");
	              $('#loginPwd').attr("placeholder","用户名或密码不正确");
	              loadingBgRemove();//关闭遮盖层
	            }else if(data.msg=="errorEmail"){
	              $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	                 inputAssert($('#loginName'));
	                   $('#loginName').val("");
	                   $('#loginName').css("border-color","red");
	                 $('#loginName').attr("placeholder","该邮箱未激活，不能登录");
	                 loadingBgRemove();//关闭遮盖层
	            }else if(data.msg=="errorPhone"){
	              $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	                 inputAssert($('#loginName'));
	                   $('#loginName').val("");
	                   $('#loginName').css("border-color","red");
	                 $('#loginName').attr("placeholder","该手机号未激活，不能登录");
	                 loadingBgRemove();//关闭遮盖层
                }else if(data.msg=="occupyPhone"){
	            	var redisId = data.obj;
                    loadingBgRemove();//关闭遮盖层
                    window.location.href=ctx+'/userCenter/relievePhoneOccup/'+redisId;
	             }else{
	                $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	                inputAssert($('#loginPwd'));
	                $('#loginPwd').val("");
	                $('#loginPwd').focus();
	                $('#loginPwd').attr("placeholder",data.msg);
	                loadingBgRemove();//关闭遮盖层
	              }
	          }    
	        }
	      }); 
	  }
	}
    function assertMsg(errorMsg){
		$.gritter.add({
			title:'提示信息',
			text:errorMsg,
			sticky:false
		});
	}
    
    
	    function  checkEmpty (){
		      var loginName = $('#loginName').val();
		      var loginPwd = $('#loginPwd').val();
		      var random = $('#verificationCode').val();
		      if (loginName == null || loginName == ""){
		    	  loadingBgRemove();//关闭遮盖层
		    	  inputAssert($('#loginName'));
			      $('#loginName').val("");
			      $('#loginName').attr("placeholder","请输入证件号码");
			      
			      return false;
		      }else if (loginPwd == null || loginPwd == ""){
		    	  loadingBgRemove();//关闭遮盖层
			      inputAssert($('#loginPwd'));
			      $('#loginPwd').val("");
			      $('#loginPwd').attr("placeholder","请输入密码");
			      
			      return false;
		      }else if(random == null || random == ""){
		    	  loadingBgRemove();//关闭遮盖层
		          inputAssert($('#verificationCode'));
			      $('#verificationCode').val("");
			      $('#verificationCode').attr("placeholder","请输入验证码");
			      
			      return false;
		      }else {
		       
		    	  return true;
		      }
	    }
	
	  /* 文本框抖动效果 */
	  function inputAssert(obj) {
	    var count=1,interval=0;
	    var u;
	    u=setInterval(function(){
	      
	      if(count>5){
	        clearInterval(u);
	      }
	      interval=count++%2==1 ?18:0;
	      $(obj).animate({marginLeft:""+interval},90);
	      
	    },32);
	
	  }
	  
	  function flashCode(){
          $('#kaptchaImage').hide().attr('src', ctx+'/login/createCode?' + Math.floor(Math.random()*100) ).fadeIn();
	  }
  
	  function initPostData(formDatas,returnUrl){
	  	 var obj=eval("["+formDatas+"]");
	       $(obj).each(function(){
			  	
		            for(var key in this){
	
		                var str="<input type=\"hidden\" name=\""+key+"\" value=\""+this[key]+"\"/>"
		                $('#hidForm').attr("action",returnUrl);
		                $('#hidForm').append(str);
	
		            }
		            
	       });
	  }
  
	  function trim(str){ //删除左右两端的空格　　
	       return str.replace(/(^\s*)|(\s*$)/g, "");
	  } 
	  /* 跳转到首页 */
	  function jumpIndex(){
	   // window.location.href='http://bec.roshan.top';
	  }